﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using NokiaMapReCode.Resources;
using Windows.Devices.Geolocation;
using Microsoft.Phone.Maps.Controls;
using Microsoft.Phone.Maps;
using System.Device.Location;
using Microsoft.Phone.Maps.Toolkit;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Collections.ObjectModel;

namespace NokiaMapReCode
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            GetCurrentCoordinate();

        }
        // Viet Ham Lay thong tin toa do hien tai : 
        Geolocator geolocator = null;
        Geoposition myGeoposition = null;
        private async void GetCurrentCoordinate()
        {
            geolocator = new Geolocator();
            geolocator.DesiredAccuracy = PositionAccuracy.High;
            geolocator.MovementThreshold = 20;
            geolocator.ReportInterval = 100;
            myGeoposition = await geolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10));
            geolocator.PositionChanged += geolocator_PositionChanged;
        }
        private void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                  
                    // Geocoordinate thể hiện Location như một tọa độ địa lý theo những qui ước chung
                    Geocoordinate geocoordinate = args.Position.Coordinate;
                    // Set View Cho map nay co chua su thay doi cua toa do 

                    myMap.SetView(geocoordinate.ToGeoCoordinate(), 16, MapAnimationKind.Parabolic);
                    // Location marker hien thi doi tuong do hoa tai vi tri nguoi dung
                    UserLocationMarker marker = (UserLocationMarker)this.FindName("UserLocationMarker");
                    marker.GeoCoordinate = geocoordinate.ToGeoCoordinate();
                    // Pushpin nay co the chua vi tri dia ly 

                    Pushpin mypushpin = (Pushpin)this.FindName("mypushpin");
                    mypushpin.GeoCoordinate = geocoordinate.ToGeoCoordinate();
                    //currentLatitude = args.Position.Coordinate.Latitude.ToString();
                    //currentLongitude = args.Position.Coordinate.Longitude.ToString();
                    //if (!isPosSet)
                    //{
                    //    isPosSet = true;
                    //    startGeoNamesAPICall();
                    //}
                    myPositionChanged(args);
                  
                });
        }
        void myPositionChanged(PositionChangedEventArgs e)
        {
            currentLatitude =txtLat.Text= e.Position.Coordinate.Latitude.ToString();
            currentLongitude =txtLng.Text= e.Position.Coordinate.Longitude.ToString();
            //MessageBox.Show("Latitude: " + latitude + "\n Longitude: " + longitude);

            if (!isPosSet)
            {
                isPosSet = true;
                startGeoNamesAPICall();
            }


        }
        private void btnLocationMe_click(object sender, EventArgs e)
        {
            GetCurrentCoordinate();
        }
        string LandMarkName = "";
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e); // Ke thua - base : constructor Cai nay vi khi chuyen trang co mang theo tham so 
            string msg = "";
            if (NavigationContext.QueryString.TryGetValue("msg", out msg))
                LandMarkName = msg;
        }

        private void btnPageLandMark_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/ChoosingPlaces.xaml?msg="+LandMarkName, UriKind.Relative));
        }
        private void startGeoNamesAPICall()
        {
            try
            {
                HttpWebRequest httpReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(AppConstants.baseUri+currentLatitude+","+currentLongitude+"&radius=3000&name="+LandMarkName+"&sensor=false&key=AIzaSyAmNV4ha3NUx_u3ykLakrOIlNMu5J3ooBQ"));
                httpReq.BeginGetResponse(HTTPWebRequestCallBack, httpReq);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void HTTPWebRequestCallBack(IAsyncResult result)
        {
            string strRespone = "";
            try
            {
                Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        HttpWebRequest httpRequest = (HttpWebRequest)result.AsyncState;
                        WebResponse response = httpRequest.EndGetResponse(result);
                        Stream stream = response.GetResponseStream();
                        StreamReader reader = new StreamReader(stream);
                        strRespone = reader.ReadToEnd();

                        parseResponseData(strRespone);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private string currentLatitude = string.Empty;
        private string currentLongitude = string.Empty;
        private string prevLatitude = string.Empty;
        private string prevLongitude = string.Empty;
        PlacesList placesListObj;
        private Boolean isPosSet = false;
        // Constructor



        private void parseResponseData(String aResponse)
        {
            placesListObj = new PlacesList();

            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(aResponse));
            DataContractJsonSerializer ser = new DataContractJsonSerializer(placesListObj.GetType());
            placesListObj = ser.ReadObject(ms) as PlacesList;
            ms.Close();

            // updating UI
            if (placesListObj != null)
            {
                updateMap(placesListObj);
            }
        }
        private void updateMap(PlacesList googlePlaceApiRespone)
        {
            int totalRecords = googlePlaceApiRespone.PlaceList.Count();
            try
            {
                ObservableCollection<PlaceToMap> placeToMapObjs = new ObservableCollection<PlaceToMap>();
                for (int index = 0; index < totalRecords; index++)
                {
                    placeToMapObjs.Add(new PlaceToMap()
                    {
                        Coordinate = new GeoCoordinate(Convert.ToDouble(googlePlaceApiRespone.PlaceList.ElementAt(index).Latitude),
                                        Convert.ToDouble(googlePlaceApiRespone.PlaceList.ElementAt(index).Longitude)),
                        Info = googlePlaceApiRespone.PlaceList.ElementAt(index).Name + Environment.NewLine + googlePlaceApiRespone.PlaceList.ElementAt(index).Vicinity
                    });
                }

                ObservableCollection<DependencyObject> children = MapExtensions.GetChildren(myMap);
                var obj = children.FirstOrDefault(x => x.GetType() == typeof(MapItemsControl)) as MapItemsControl;

                obj.ItemsSource = placeToMapObjs;
                myMap.SetView(new GeoCoordinate(Convert.ToDouble(currentLatitude), Convert.ToDouble(currentLongitude)), 14);
            }
            catch (Exception)
            {

            }
        }


    }

}